
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../config/const_config.dart';
import '../config/string_config.dart';
import '../models/qr_code_parser_entity.dart';
import 'local_storage.dart';


class QRCodeParser {
  static const String _TAG = "QRCodeParser";

  // 解析二维码内容
  static Future<QRCodeParserEntity> parseQRCode(String scannedContent) async {
    QRCodeParserEntity result = QRCodeParserEntity();

    try {
      // 使用正则表达式匹配尖括号中的内容
      RegExp pattern = RegExp(r'<(.*?)>');
      Iterable<RegExpMatch> matches = pattern.allMatches(scannedContent);
    if(matches.isEmpty){
      result = QRCodeParserEntity();
      result.isValid = false;
      result.errorTitle = StringConfig.invalid_qr_code;
      result.errorMessage = StringConfig.scan_valid_qr_code;
      return result;
    }
      for (RegExpMatch match in matches) {
        String deviceName = match.group(1) ?? '';

        if (deviceName.length == 3) {
          // machine num格式
          result.isValid = true;
          result.type = ConstConfig.MACHINE_NUM;
          result.oldQrCode = deviceName;
          result.deviceName = deviceName;
        } else if (deviceName.length == 18 && deviceName.startsWith('TTI')) {
          // 第一种旧WiFi名称格式
          String deviceSNO = deviceName.substring(12, 18);
          result.isValid = true;
          result.type = ConstConfig.MACHINE_OLD;
          result.deviceSNO = deviceSNO;
          result.deviceName = deviceName;
        } else if (deviceName.length == 16) {
          // 新WiFi名称格式
          String deviceSNO = deviceName.substring(10, 16);
          String productCode = deviceName.substring(8, 10);
          result.isValid = true;
          result.type = ConstConfig.MACHINE_NEW;
          result.deviceSNO = deviceSNO;
          result.deviceName = deviceSNO;
          result.productCode = productCode;
          debugPrint('$_TAG: deviceName: $deviceName');
          debugPrint('$_TAG: productCode: $productCode, deviceSNO: $deviceSNO');
        } else if (deviceName.length == 7) {
          // src
          result.isValid = true;
          result.type = ConstConfig.SRC_CODE;
          result.src = deviceName;
          LocalStorage.save(ConstConfig.SRC_CODE, deviceName);
        } else {
          // 无效格式
          result.isValid = false;
          result.errorTitle = StringConfig.invalid_qr_code;
          result.errorMessage = StringConfig.scan_valid_qr_code;
        }

        // 找到第一个匹配项后退出循环
        break;
      }
    } catch (e) {
      debugPrint('$_TAG: Error parsing QR code: $e');
      result = QRCodeParserEntity();
      result.isValid = false;
      result.errorTitle = StringConfig.invalid_qr_code;
      result.errorMessage = StringConfig.scan_valid_qr_code;
    }

    return result;
  }
}